package com.fc.happyteam.api;

import com.fc.happyteam.common.upload.FileUploadManager;
import com.fc.happyteam.utils.R;
import org.apache.commons.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class FileUploadController {

    @Autowired
    private FileUploadManager fileUploadManager;

    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String upload() {
        return "/fileupload";
    }

    // 访问路径为：http://ip:port/upload/batch
    @RequestMapping(value = "/upload/batch", method = RequestMethod.GET)
    public String batchUpload() {
        return "/mutifileupload";
    }

    /**
     * 文件上传具体实现方法（单文件上传）
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public R upload(@RequestParam("file") MultipartFile file) throws FileUploadException {
        String path = fileUploadManager.upload(file);
        return R.ok().put("uploaded", new String[]{path});
    }

    /**
     * 多文件上传 主要是使用了MultipartHttpServletRequest和MultipartFile
     * @param request
     * @return
     */
    @RequestMapping(value = "/upload/batch", method = RequestMethod.POST)
    public @ResponseBody
    R batchUpload(HttpServletRequest request) throws FileUploadException {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        String[] paths = fileUploadManager.batchUpload(files);
        return R.ok().put("uploaded", paths);
    }
}
